package com.dingding.order.core.publish.biz.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.dingding.common.core.beans.Userdetail;
import com.dingding.common.core.beans.Userordert;
import com.dingding.common.core.config.ServiceCode;
import com.dingding.common.core.util.DateFormatUtil;
import com.dingding.common.core.util.JSONUtil;
import com.dingding.facade.queue.dto.business.BusinessRequestDTO;
import com.dingding.facade.queue.dto.push.PushRequestDTO;
import com.dingding.facade.queue.enums.ClientType;
import com.dingding.facade.queue.enums.PushType;
import com.dingding.facade.queue.facade.IQueueFacade;
import com.dingding.facade.user.dto.order.ReqGetAllCityWideUserDTO;
import com.dingding.facade.user.dto.order.ResGetAllCityWideUserDTO;
import com.dingding.facade.user.facade.order.IOrderUserFacade;
import com.dingding.facade.user.service.IUserInfoFacade;
import com.dingding.order.core.publish.biz.IRegularRoutePushService;
import com.dingding.order.core.publish.dao.IPublishOrderDao;
import com.dingding.order.core.publish.sql.RegularRoutePushSql;
import com.dingding.order.dto.publish.AuroraPushBean;
import com.dingding.order.dto.publish.PushData;

/**
 * 
 * @ClassName: IRegularRoutePushService
 * @Description: 顺路订单推送业务处理
 * @author YHQ
 * @date 2016年6月3日 下午12:02:35
 * 
 */
@Component("regularRoutePushService")
public class RegularRoutePushServiceImpl implements IRegularRoutePushService {

	private Logger log = Logger.getLogger(this.getClass());

	@Resource(name = "publishOrderDao")
	private IPublishOrderDao publishOrderDao;

	@Resource(name = "userInfoService")
	private IUserInfoFacade userInfoService;

	@Resource(name = "queueService")
	private IQueueFacade queueFacade;

	@Resource(name = "orderFacade_cus")
	private IOrderUserFacade orderUserFacade;

	/**
	 * 
	 * @Title: regularRoutePush
	 * @Description: 顺路推送
	 * @param userType 下单用户角色
	 * @param userordert 订单信息
	 * @author YHQ
	 * @return void 返回类型
	 * 
	 */
	@Override
	public void regularRoutePush(Userordert userordert) {

		// 查询当前发布订单人的信息
		Userdetail userdetail = userInfoService.getUserDetail(userordert.getPlaceOrderUserId());

		if (userdetail != null) {
			ReqGetAllCityWideUserDTO reqGetAllCityWideUserDTO = new ReqGetAllCityWideUserDTO();
			// 下单城市
			reqGetAllCityWideUserDTO.setCity(userordert.getPayCity());
			// 下单用户类型
			reqGetAllCityWideUserDTO.setLoginId(userordert.getPlaceOrderUserId());
			// 下单类型(用户角色 1:司机 2:乘客)
			reqGetAllCityWideUserDTO.setPublishType(userordert.getOrderType());

			// 获取符合条件的全部用户
			List<ResGetAllCityWideUserDTO> resGetAllCityWideUserDTOs = orderUserFacade
					.getAllCityWideUserByCity(reqGetAllCityWideUserDTO);

			// 将该订单信息发送给符合条件的用户
			for (ResGetAllCityWideUserDTO resGetAllCityWideUserDTO : resGetAllCityWideUserDTOs) {
				
				// 用户当天推送次数小于三次可以进行推送，等于或大于三次，则不进行推送
				if(resGetAllCityWideUserDTO.getPushNumber() == null || resGetAllCityWideUserDTO.getPushNumber() < 3){
					
					createPushContent(resGetAllCityWideUserDTO,userordert);
				}
				
			}

		}

	}

	/**
	 * 
	 * @Title: createPushContent
	 * @Description: 将推送内容加入队列
	 * @param resGetAllCityWideUserDTO
	 * @param userordert 
	 * @author yuHaiQing
	 * @return void    返回类型
	 * 
	 */
	private void createPushContent(ResGetAllCityWideUserDTO resGetAllCityWideUserDTO,Userordert userordert) {

		PushRequestDTO pushRequestDTO = new PushRequestDTO();
		
		BusinessRequestDTO businessRequestDTO = new BusinessRequestDTO();

		// 用户Id
		businessRequestDTO.setUserId(resGetAllCityWideUserDTO.getUid());
		
		// 推送别名
		pushRequestDTO.setAliasId(resGetAllCityWideUserDTO.getAliasId());

		// 设置推送的设备类型
		if (resGetAllCityWideUserDTO.getLoginEquipment() == 1) {
			pushRequestDTO.setClientType(ClientType.iOS);
		} else if (resGetAllCityWideUserDTO.getLoginEquipment() == 2) {
			pushRequestDTO.setClientType(ClientType.Android);
		}

		// 用户下单推送，自定义参数
		Map<String, String> map = new HashMap<String, String>();

		map.put("oid", userordert.getOid()); // 订单Id
		map.put("orderType", userordert.getOrderType().toString());// 下单类型(1:乘客下单
																	// 2:司机下单)
		map.put("modular", ServiceCode.CURRENTCITY_PUSH); // modular(接口名)
		
		// 通知标题
		String title = "[顺路推送]";

		title = this.setTitle(title, userordert);
		// 自定义标题
		pushRequestDTO.setMsgTitle(title);
		// 通知标题
		pushRequestDTO.setAlert(title);
		// 消息推送类型
		pushRequestDTO.setPushType(PushType.alert_extra);

		pushRequestDTO.setMap(map);
		
		// 推送消息加入队列
		queueFacade.addPushToQueue(JSONUtil.toJSONString(pushRequestDTO));

		// 用户每日推送次数加一  加入队列
		queueFacade.addPushNumberToQueue(JSONUtil.toJSONString(businessRequestDTO));
		
	}

	/**
	 * 
	 * @Title: getUserListByPush
	 * @Description: 获取符合推送条件的用户列表
	 * @param userordert 订单信息
	 * @author YHQ
	 * @return List<Object[]> 返回类型
	 * 
	 */
	@Transactional(readOnly = true)
	public List<Object[]> getUserListByPush(Userordert userordert) {

		// 获取下单用户
		String placeOrderUserId = userordert.getPlaceOrderUserId();
		// 获取用户下单类型
		Integer userType = userordert.getOrderType();

		// 获取符合条件的用户列表
		List<Object[]> objects = null;
		try {

			// 获取符合条件的用户列表
			objects = publishOrderDao.listSqlObj(RegularRoutePushSql.GET_PUSH_USER_INFO(userType), placeOrderUserId);

		} catch (Exception e) {
			log.error("用户下单推送，获取符合条件的用户列表时出现异常   类：" + this.getClass() + " pushToCurrentUsers()", e);
		}

		return objects;
	}

	/**
	 * @Title: getAuroraPushBeanList 
	 * @Description: 获取推送列表 
	 * @param objects 要推送的用户列表
	 * @param userordert 订单信息
	 * @author YHQ 
	 * @return List<AuroraPushBean>    返回类型
	 */
	public List<AuroraPushBean> getAuroraPushBeanList(List<Object[]> objects, Userdetail userdetail,
			Userordert userordert) {

		// 创建存储推送信息列表
		List<AuroraPushBean> auroraPushBeans = new ArrayList<AuroraPushBean>();

		// 去重(去除重复出现的用户)
		this.duplicateRemoval(objects);

		if (objects.size() > 0) {

			for (Object[] obj : objects) {

				// 相同城市就推送
				int number = obj[10].toString().indexOf(userdetail.getCurrentCity());

				// 属于同城，进行推送
				if (number > 0) {
					this.getAuroraPushBean(obj, userdetail, userordert);
				}
			}
		}

		return auroraPushBeans;
	}

	/**
	 * @Title: getAuroraPushBean 
	 * @Description: 获取推送列表
	 * @param  obj
	 * @param  userdetail 用户详情
	 * @param  userordert
	 * @author YHQ 
	 * @return AuroraPushBean    返回类型
	 */
	public void getAuroraPushBean(Object[] obj, Userdetail userdetail, Userordert userordert) {

		PushRequestDTO pushRequestDTO = new PushRequestDTO();

		// 推送别名
		pushRequestDTO.setAliasId(obj[5].toString());

		if (obj[6] != null && obj[6].toString().equals("1")) {
			// 设备类型
			pushRequestDTO.setClientType(ClientType.iOS);
		} else if (obj[6] != null && obj[6].toString().equals("2")) {
			// 设备类型
			pushRequestDTO.setClientType(ClientType.Android);
		}

		// 推送内容
		String msgContent = this.getPushData(ServiceCode.CURRENTCITY_PUSH);

		// 通知标题
		String title = "[顺路推送]";

		title = this.setTitle(title, userordert);
		// 自定义标题
		pushRequestDTO.setMsgTitle(title);
		// 通知标题
		pushRequestDTO.setAlert(title);
		// 消息推送类型
		pushRequestDTO.setPushType(PushType.alert_msgcontent);

		pushRequestDTO.setPushContent(msgContent);

		// 推送消息加入队列
		queueFacade.addPushToQueue(JSONUtil.toJSONString(pushRequestDTO));

	}

	/**
	 * @Title: getPushData 
	 * @Description: 推送内容
	 * @param modular 模块名称
	 * @author YHQ 
	 * @return String    返回类型
	 */
	public String getPushData(String modular) {

		// 创建推送数据
		PushData pushData = new PushData();
		// 推送序号(时间戳)
		pushData.setRequestNumber(DateFormatUtil.getTimeInMillis().toString());
		// 推送时间
		pushData.setRequestTime(DateFormatUtil.yyyy_MM_dd_HHmmss());
		// 模块
		pushData.setModular(modular);

		// 同城推送暂不添加内容
		pushData.setResponseBody(null);

		String msgContent = JSONUtil.toJSONString(pushData, "yyyy-MM-dd HH:mm:ss"); // 推送内容

		return msgContent;
	}

	/**
	 * 同城推送，设置推送标题
	 */
	public String setTitle(String alert, Userordert userordert) {

		// 获取出发时间字符串
		String dateStr = this.getDateStr(userordert.getSetOutTime());

		alert += "时间：" + dateStr;
		
		alert += ",从" + userordert.getStartAddress() + "到" + userordert.getEndAddress();

		return alert;
	}

	// 判断出发时间是否为今天，并返回时间字符串
	public String getDateStr(Date setOutTime) {

		StringBuilder dateStr = new StringBuilder();

		// 判断时间段
		Calendar calendarSetOutTime = Calendar.getInstance();

		// 将订单的出发时间赋给calendarSetOutTime
		calendarSetOutTime.setTime(setOutTime);

		// 系统当前时间
		Calendar calendarCurrent = Calendar.getInstance();

		// 设置时间格式
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd");

		// 获取出发时间的年月日
		String setOutTimeDate = sdf.format(calendarSetOutTime.getTime());

		// 获取当前时间的年月日
		String currentDate = sdf.format(calendarCurrent.getTime());

		// 判断出发日期是否为当日
		if (setOutTimeDate.equals(currentDate)) {
			dateStr.append("今天 ");
		} else {
			dateStr.append(new SimpleDateFormat("MM月dd日").format(calendarSetOutTime.getTime()));
		}

		dateStr.append(new SimpleDateFormat("HH : mm").format(calendarSetOutTime.getTime()));

		return dateStr.toString();
	}

	/**
	 * @Title: duplicateRemoval 
	 * @Description: 去重 
	 * @author yuHaiQing 
	 * @return void 返回类型 
	 */
	public void duplicateRemoval(List<Object[]> objects) {

		// 去重(去除集合中重复的用户信息)
		for (int i = 0; i < objects.size(); i++) {// 外循环是循环的次数

			for (int j = objects.size() - 1; j > i; j--) {// 内循环是 外循环一次比较的次数

				// 判断中别名是否有重复的，如果有，则移除。
				if (objects.get(i) != null && objects.get(j) != null && objects.get(i)[5] != null
						&& objects.get(j)[5] != null && objects.get(i)[5] == objects.get(j)[5]) {
					objects.remove(j);// 移除重复的用户
				}
			}
		}
	}

}
